<template>
  <div class="container">
    <!-- 搜索条件-->
    <el-form :inline="true" :model="query" ref="queryForm" class="demo-form-inline">
      <el-form-item label="角色名称" prop="name">
        <el-input v-model="query.name" placeholder="请输入角色名称"></el-input>
      </el-form-item>

      <el-form-item label="权限标识" prop="perms">
        <el-input v-model="query.perms" placeholder="请输入权限标识"></el-input>
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-select v-model="query.status" placeholder="请选择" clearable>
          <el-option v-for="item in statusList" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="创建时间">
        <el-date-picker
          v-model="createDate"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
        >
        </el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="small" @click="search">查询</el-button>
        <el-button type="primary" icon="el-icon-refresh" size="small" @click="resetForm" plain>重置</el-button>
      </el-form-item>
    </el-form>
    <!--工具条-->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
        >导出</el-button>
      </el-col>
    </el-row>
    <!-- 画表格-->
    <el-table :loading="loading" :data="roleList"  style="width: 100%" border @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"></el-table-column>
      <el-table-column prop="id" label="角色编号" width="100"></el-table-column>
      <el-table-column prop="name" label="角色名称" width="250"></el-table-column>
      <el-table-column prop="perms" label="权限字符" width="250"></el-table-column>
      <el-table-column prop="sorts" label="显示顺序" width="150"></el-table-column>
      <el-table-column prop="status" label="状态" width="150">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            active-value="0"
            inactive-value="1"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="250"></el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope" v-if="scope.row.id !== 1">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
          <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)">
            <span class="el-dropdown-link">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-d-arrow-right"
              >更多</el-button>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item
                command="handleDataScope"
                icon="el-icon-circle-check"
                >数据权限</el-dropdown-item>
              <el-dropdown-item
                command="handleAuthUser"
                icon="el-icon-user"
                >分配用户</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <!-- 画分页条 -->
    <div v-show="total>0"  class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="query.page"
        :page-sizes="[10, 20, 30, 50,100]"
        layout="total, sizes, prev, pager, next, jumper"
        :page-size="query.size"
        :total="total">
      </el-pagination>
    </div>
    <!--添加或修改角色对话框-->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item prop="perms">
      <span slot="label">
        <el-tooltip content="控制器中定义的权限字符，如：@PreAuthorize(`@ss.hasRole('admin')`)" placement="top">
          <i class="el-icon-question"></i>
        </el-tooltip>
        权限字符
      </span>
          <el-input v-model="form.perms" placeholder="请输入权限字符" />
        </el-form-item>
        <el-form-item label="角色顺序" prop="sorts">
          <el-input-number v-model="form.sorts" controls-position="right" :min="0" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in statusList"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="菜单权限">
          <el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand($event, 'menu')">展开/折叠</el-checkbox>
          <el-checkbox v-model="menuNodeAll" @change="handleCheckedTreeNodeAll($event, 'menu')">全选/全不选</el-checkbox>
          <el-checkbox v-model="form.menuCheckStrictly" @change="handleCheckedTreeConnect($event, 'menu')">父子联动</el-checkbox>
          <el-tree
            class="tree-border"
            :data="menuOptions"
            show-checkbox
            ref="menu"
            node-key="menuId"
            :check-strictly="!form.menuCheckStrictly"
            empty-text="加载中，请稍候"
            :props="defaultProps"
          ></el-tree>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 分配角色数据权限对话框 -->
    <el-dialog :title="title" :visible.sync="openDataScope" width="500px" append-to-body>
      <el-form :model="form" label-width="80px">
        <el-form-item label="角色名称">
          <el-input v-model="form.name" :disabled="true" />
        </el-form-item>
        <el-form-item label="权限字符">
          <el-input v-model="form.perms" :disabled="true" />
        </el-form-item>
        <el-form-item label="权限范围">
          <el-select v-model="form.dataScope" @change="dataScopeSelectChange">
            <el-option
              v-for="item in dataScopeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="数据权限" v-show="form.dataScope == 2">
          <el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand($event, 'dept')">展开/折叠</el-checkbox>
          <el-checkbox v-model="menuNodeAll" @change="handleCheckedTreeNodeAll($event, 'dept')">全选/全不选</el-checkbox>
          <el-checkbox v-model="form.menuCheckStrictly" @change="handleCheckedTreeConnect($event, 'dept')">父子联动</el-checkbox>
          <el-tree
            class="tree-border"
            :data="menuOptions"
            show-checkbox
            default-expand-all
            ref="dept"
            node-key="id"
            :check-strictly="!form.menuCheckStrictly"
            empty-text="加载中，请稍候"
            :props="defaultProps"
          ></el-tree>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitDataScope">确 定</el-button>
        <el-button @click="cancelDataScope">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getData, addRole, updateRole, delRole, getRoleDetail, dataScope, changeRoleStatus } from '@/api/role.js'
import { roleMenuTreeSelect, roleMenuTreeSelectById } from '@/api/menu/menu'

export default {
  name: 'Role',
  data() {
    return {
      // 遮罩层
      loading: true,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 导出遮罩层
      exportLoading: false,
      // 对话框标题
      title: '',
      // 表单参数
      form: {},
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      // 选中数组
      ids: [],
      // 菜单列表
      menuOptions: [],
      // 是否显示弹出层
      open: false,
      // 是否显示弹出层(数据权限)
      openDataScope: false,
      menuExpand: false,
      menuNodeAll: false,
      // 数据范围选项
      dataScopeOptions: [
        {
          value: '1',
          label: '全部数据权限'
        },
        {
          value: '2',
          label: '自定数据权限'
        }
      ],
      // 搜索条件
      query: {
        name: undefined,
        perms: undefined,
        status: undefined,
        page: 1,
        size: 10
      },
      // 状态列表
      statusList: [{
        label: '正常',
        value: '0'
      }, {
        label: '停用',
        value: '1'
      }],
      // 时间选择器的值
      createDate: [],
      // 分页结果
      total: 0,
      roleList: [],
      // 表单校验
      rules: {
      }
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    // 点击查询按钮的事件
    search() {
      this.query.page = 1
      this.fetchData()
    },
    // 重置搜索表单
    resetForm() {
      this.$refs['queryForm'].resetFields()
      this.createDate = []
    },
    // 当每页显示多少发生变化
    handleSizeChange(val) {
      this.query.size = val
      // 查询数据
      this.fetchData()
    },
    // 点击了第几页
    handleCurrentChange(val) {
      this.query.page = val
      // 查询数据
      this.fetchData()
    },
    // 查询角色表数据
    fetchData() {
      this.loading = true
      getData(this.addDateRange(this.query, this.createDate)).then(resp => {
        if (resp.code === 0) {
          this.total = resp.count
          this.roleList = resp.data
          this.loading = false
        } else {
          this.$message.error(resp.msg)
        }
      }).catch(e => {
        this.$message.error(e)
      })
    },
    // 查询菜单树结构
    getMenuTreeSelect() {
      roleMenuTreeSelect().then(resp => {
        this.menuOptions = resp.data
      })
    },
    // 所有菜单节点数据
    getMenuAllCheckedKeys() {
      // 目前被选中的菜单节点
      const checkedKeys = this.$refs.menu.getCheckedKeys()
      // 半选中的菜单节点
      const halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys()
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys)
      return checkedKeys
    },
    // 根据角色ID查询菜单树结构
    getRoleMenuTreeSelectById(roleId) {
      return roleMenuTreeSelectById(roleId).then(resp => {
        this.menuOptions = resp.data
        return resp
      })
    },
    // 角色状态修改
    handleStatusChange(row) {
      const text = row.status === '0' ? '启用' : '停用'
      this.$confirm('确认要"' + text + '""' + row.name + '"角色吗', '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        changeRoleStatus(row.id, row.status)
        this.$message({
          type: 'success',
          message: '修改成功'
        })
      }).catch(function() {
        row.status = row.status === '0' ? '1' : '0'
      })
    },
    // 新增按钮
    handleAdd() {
      this.reset()
      // 调用查询所有菜单的方法
      this.getMenuTreeSelect()
      this.open = true
      this.title = '新增角色'
    },
    // 修改按钮
    handleUpdate(row) {
      this.reset()
      const roleId = row.id || this.ids
      // 调用根据角色roleId查询菜单的方法
      // const roleMenu = this.getRoleMenuTreeSelectById(roleId)
      getRoleDetail(roleId).then(resp => {
        this.form = resp.data
        this.open = true
        this.$nextTick(() => {
          // roleMenu.then(res => {
          //   console.log(res)
          //   const checkedKeys = res.checkedKeys
          //   checkedKeys.forEach((v) => {
          //     this.$nextTick(() => {
          //       this.$refs.menu.setChecked(v, true, false)
          //     })
          //   })
          // })
        })
        this.title = '修改角色'
      })
    },
    // 删除按钮
    handleDelete(row) {
      const roleId = row.id || this.ids
      this.$confirm('是否删除角色编号为"' + roleId + '"的数据项?', '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delRole(roleId)
        this.$message({
          type: 'success',
          message: '删除成功'
        })
        this.fetchData()
      }).catch(() => {})
    },
    // 导出按钮
    handleExport() {
    },
    // 表单重置
    reset() {
      if (this.$refs.menu !== undefined) {
        this.$refs.menu.setCheckedKeys([])
      }
      this.menuExpand = false
      this.menuNodeAll = false
      this.deptExpand = true
      this.deptNodeAll = false
      this.form = {
        id: undefined,
        name: undefined,
        perms: undefined,
        sorts: 0,
        status: '0',
        menuIds: [],
        menuCheckStrictly: true
      }
      this.resetForm('form')
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 取消按钮(数据权限)
    cancelDataScope() {
      this.openDataScope = false
      this.reset()
    },
    // 提交按钮
    submitForm() {
      // 开启验证
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id !== undefined) {
            // 查询所有菜单节点数据
            updateRole(this.form).then(resp => {
              this.$message({
                type: 'success',
                message: '修改成功'
              })
            })
            this.open = false
            this.fetchData()
          } else {
            // 查询所有菜单节点数据
            addRole(this.form).then(resp => {
              this.$message({
                type: 'success',
                message: '新增成功'
              })
            })
            this.open = false
            this.fetchData()
          }
        }
      })
    },
    // 提交按钮(数据权限)
    submitDataScope() {
      if (this.form.id !== undefined) {
        dataScope(this.form).then(resp => {
          this.$message({
            type: 'success',
            message: '修改成功'
          })
          this.openDataScope = false
          this.fetchData()
        })
      }
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    // 树权限（展开/折叠）
    handleCheckedTreeExpand(value, type) {
      if (type === 'menu') {
        const treeList = this.menuOptions
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.menu.store.nodesMap[treeList[i].id].expanded = value
        }
      }
    },
    // 树权限（全选/全不选）
    handleCheckedTreeNodeAll(value, type) {
      if (type === 'menu') {
        this.$refs.menu.setCheckedNodes(value ? this.menuOptions : [])
      }
    },
    // 树权限（父子联动）
    handleCheckedTreeConnect(value, type) {
      if (type === 'menu') {
        this.form.menuCheckStrictly = value ? true : false
      }
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case 'handleDataScope':
          this.handleDataScope(row)
          break
        case 'handleAuthUser':
          this.handleAuthUser(row)
          break
        default:
          break
      }
    },
    // 分配数据权限
    handleDataScope(row) {
      this.reset()
      const roleMenuTreeSelect = this.getRoleMenuTreeSelectById(row.id)
      getRoleDetail(row.id).then(resp => {
        this.form = resp.data
        this.openDataScope = true
        this.$nextTick(() => {
          roleMenuTreeSelect.then(res => {
            this.$refs.menu.setCheckedKeys(res.checkedKeys)
          })
        })
        this.title = '分配数据权限'
      })
    },
    // 选择角色权限范围触发
    dataScopeSelectChange(value) {
      if (value !== '2') {
        this.$refs.menu.setCheckedKeys([])
      }
    },
    // 分配用户
    handleAuthUser: function(row) {
      const roleId = row.id
      this.$router.push('/system/role-auth/user/' + roleId)
    }
  }
}
</script>

<style>
</style>
